#! -*- coding: UTF-8 -*-
'''
PowerSlim is an IronPython bridge to PowerShell
PowerSlim is a generic action for Fitnesse+SLIM acceptanse tests (http://fitnesse.org/FitNesse.SliM).
You need to use it in conjunction with waferslim 1+ (http://code.launchpad.net/waferslim).
PowerShell 2.0 should be installed on SLIM server side (http://support.microsoft.com/kb/968929).
Home: http://vlasenko.org/powerslim/
Copyright 2010 by the author(s). All rights reserved  
'''
__version__ = "0.1"
import os,re
import clr,os	
clr.AddReference("System.Management")
clr.AddReference("System.Management.Automation")
from System.Management.Automation import *
from System.Management.Automation.Host import *
from System.Management.Automation.Runspaces import *
from System.Management.Automation.Runspaces import RunspaceFactory



class PowerShellWrapper:
	def __init__(self,alias = lambda x:x):
		self.runspace		= RunspaceFactory.CreateRunspace()
		self.runspace.Open()
		self.ri 			= RunspaceInvoke(self.runspace)
		self.output 		= []
		self._alias 		= alias
		self.error			= ""
	
	
	def include(self,files=[]):
		for fl in files:
			self.cmd( open(fl).read() )
		return self
	
	# run q and fill output
	def cmd(self,q):
		self.output = self.ri.Invoke( self._alias(q) )
		self.error  = "".join([ str(i) for i in self.ri.Invoke( "$error") ]) 
		return self
	
	# try convert output to string
	def toStr(self):
		return "".join([ str(i) for i in self.output ])

	def out(self):	
		def _get_attributes(i):
			if hasattr(i.ImmediateBaseObject,"Attributes"):
				if not hasattr(i.ImmediateBaseObject.Attributes,'__iter__'):
					return []
				if hasattr(i.ImmediateBaseObject,"GetAttribute"):
					return [[k.Name,i.ImmediateBaseObject.GetAttribute(k.Name)] for k in i.ImmediateBaseObject.Attributes ]
				else:
					return [[k.Name,k.Value] for k in i.ImmediateBaseObject.Attributes if hasattr(k,"Value") ]				
			return []				
			
		def _get_property(i):
			if hasattr(i,"Properties"):
				if not hasattr(i.Properties,'__iter__'):
					return []
				return [[k.Name,k.Value] for k in i.Properties if hasattr(k,"Value") ]									
			return []

		return [ _get_attributes(i) + _get_property(i)  for i in self.output ]		       

		

		
powershell = PowerShellWrapper(alias=lambda x:x)		



def check_powershell_error(f):
	def _wrap(*args, **kwds):
		ret = f(*args, **kwds)
		if powershell.error:
			powershell.ri.Invoke( "$error.Clear()")
			return '<pre>' + powershell.error + '</pre>'
		return ret
	powershell.error = ""
	return _wrap
		
		


class PowerShell(object):

	def __init__(self, q=None):
		if q:
			self.q = q
	
	@check_powershell_error
	def eval(self,q):
		return powershell.cmd(q).toStr()

	@check_powershell_error
	def query(self):
		self.out = powershell.cmd(self.q).out()
		return self.out
	
	@check_powershell_error
	def doTable(self, rows):
		command = "%(rows)s | %% { %(script)s @%(row0)s $_ }" % {
			"rows"		: rows[1:] ,
			"script"	: self.q,
			"row0"		: rows[0],
		}
		return []
		